<?php
/**
 * Created by PhpStorm
 * @Author: wangwin
 * @Date: 2024/9/5
 * @Time: 15:40
 * @Version: 1.0
 */

namespace App\Service\Gpt;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class ChatService
{
    protected $client;
    protected $apiKey;
    protected $baseUri;
    protected $model;

    /**
     * Constructor to initialize the API service.
     *
     * @param string $apiKey
     * @param string $baseUri
     */
    public function __construct(string $apiKey, string $baseUri)
    {
        $this->apiKey = $apiKey;
        $this->baseUri = $baseUri;
        $this->client = new Client([
            'base_uri' => $this->baseUri,
        ]);
    }

    /**
     * Perform the chat completion request.
     *
     * @param array $data
     * @return array
     * @throws \Exception
     */
    public function chat(array $data)
    {
        try {
            if ($this->model) {
                $data['model'] = $this->model;
            }
            $response = $this->client->post('chat/completions', [
                'headers' => [
                    'Authorization' => 'Bearer '.$this->apiKey,
                    'Content-Type'  => 'application/json',
                ],
                'json'    => $data,
            ]);

            return json_decode($response->getBody()->getContents(), true);
        } catch (RequestException $e) {

            dd($e);
            throw new \Exception('Request failed: '.$e->getMessage());
        }
    }

    /**
     * Set the API key dynamically.
     *
     * @param string $apiKey
     * @return $this
     */
    public function setApiKey(string $apiKey): self
    {
        $this->apiKey = $apiKey;

        return $this;
    }


    /**
     * Set a new base URI for the API client.
     *
     * @param string $baseUri
     * @return $this
     */
    public function setBaseUri(string $baseUri): self
    {
        $this->baseUri = $baseUri;
        $this->client = new Client([
            'base_uri' => $this->baseUri,
        ]);

        return $this;
    }


    /**
     * Send a post request using cURL as a fallback.
     *
     * @param string $url
     * @param array $postData
     * @param array $headers
     * @return mixed
     * @throws \Exception
     */
    public function sendPostRequest($url, $postData, $headers = [])
    {
        $ch = curl_init();
        $jsonData = json_encode($postData);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new \Exception("cURL Error: $error");
        }

        curl_close($ch);

        return json_decode($response, true);
    }

    /*php artisan make:command ProcessTransaction
*
     * 实例化
     * @param string $apiKey
     * @param string $baseUri
     * @return static
     */
    public static function create(string $apiKey = '7dcae406-5eea-4ab8-b6aa-191d50288c57', string $baseUri = 'https://ark.cn-beijing.volces.com/api/v3/'): self
    {
        return new self($apiKey, $baseUri);
    }
}
